package com.bbcare.nutritious.plat.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.QueryModel;
import com.bbcare.comm.ResultModel;
import com.bbcare.comm.SeqUtil;
import com.bbcare.comm.ToolUtils;
import com.bbcare.nutritious.plat.entity.PtBloodsugarRecord;
import com.bbcare.nutritious.plat.service.IBloodSugarService;

/**
 *
 * @name:         BloodSugarController.java
 * @author:       tao
 * @createTime:   2017年11月6日
 * @description:  血糖控制器
 * @modify:
 *
 */
@Controller
@RequestMapping("/service/nutrition")
public class BloodSugarController {

    public static final Logger logger = Logger.getLogger(BloodSugarController.class);

    @Autowired
    private IBloodSugarService bloodSugarService;

    //设备绑定
    @ResponseBody
    @RequestMapping("/device/binding")
    public ResultModel<Object> deviceBind(HttpServletRequest request, @RequestBody String jsonStr)
            throws Exception {
        logger.info("in deviceBind----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        String deviceId = requestParam.getString("deviceId");
        if(StringUtils.isEmpty(deviceId)){
        	logger.debug("out deviceBind----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"设备ID不能为空");
        }

        String userId = requestParam.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.debug("out deviceBind----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"用户ID不能为空");
        }

        String type = requestParam.getString("type");
        if(StringUtils.isEmpty(type)){
        	logger.debug("out deviceBind----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"设备类型不能为空");
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
//        String deptId = (String) sessionMap.get("deptId");// 科室id
        String authorId = (String) sessionMap.get("authorId");//登陆用户id
        String tenantId = (String) sessionMap.get("tenantId");//租户科室id

        requestParam.put("tenantId",tenantId);
        requestParam.put("authorId",authorId);
        Map<String,Object> rspMap = bloodSugarService.deviceBind(requestParam);

        logger.debug("out deviceBind----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }

    //设备解绑
    @ResponseBody
    @RequestMapping("/device/unbind")
    public ResultModel<Object> deviceUnbind(HttpServletRequest request, @RequestBody String jsonStr)
            throws Exception {
        logger.info("in deviceUnbind----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        String id = requestParam.getString("id");
        if(StringUtils.isEmpty(id)){
        	logger.debug("out deviceUnbind----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"绑定id不能为空");
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
//        String deptId = (String) sessionMap.get("deptId");// 科室id
        String authorId = (String) sessionMap.get("authorId");//登陆用户id
        String tenantId = (String) sessionMap.get("tenantId");//租户科室id

        requestParam.put("tenantId",tenantId);
        requestParam.put("authorId",authorId);
        Map<String,Object> rspMap = bloodSugarService.deviceUnbind(requestParam);

        logger.debug("out deviceUnbind----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }

    //用户血糖导入
    @ResponseBody
    @RequestMapping("/bloodsugar/import")
    public ResultModel<Object> bloodsugarImport(HttpServletResponse response, HttpServletRequest request)
            throws Exception {
    	logger.info("in bloodsugarImport ");
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());

		// 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");//登陆用户id
        String tenantId = (String) sessionMap.get("tenantId");//租户科室id

		List<PtBloodsugarRecord> list = new ArrayList<PtBloodsugarRecord>();
		if (multipartResolver.isMultipart(request)) {
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                Iterator<String> iter = multiRequest.getFileNames();
                while (iter.hasNext()) {
                    MultipartFile file = multiRequest.getFile(iter.next());
                    if(!file.isEmpty()){
                    	String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1).toLowerCase();
                    	if(!"csv".equals(suffix)&& !"xlsx".equals(suffix) && !"xls".equals(suffix)){
                    		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_FILE_TYPE_INCORRECT,"文件格式不对");
                        }

                    	Workbook workbook = null;
                    	Sheet sheet = null;
                    	if(ToolUtils.isExcel2003(file.getOriginalFilename())){
                    		workbook=new HSSFWorkbook(file.getInputStream());
                    	}else if(ToolUtils.isExcel2007(file.getOriginalFilename())){
                    		workbook = new XSSFWorkbook(file.getInputStream());
                    	}

                 	    for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                 	    	//
                 	    	sheet=workbook.getSheetAt(i);
           	        	    for (int j = 1; j < sheet.getPhysicalNumberOfRows(); j++) {//获取每行  从第二行开始
           	        	    	Row row=sheet.getRow(j);
	           	 	            if(null != row && row.getPhysicalNumberOfCells()>=3){
	           	 	            	PtBloodsugarRecord record =  new PtBloodsugarRecord();
	           	 	            	String deviceId =  ToolUtils.getCellValue(row.getCell((short)0));
	           	 	            	String createTime =  ToolUtils.getCellValue(row.getCell((short)1));
	           	 	            	String value =  ToolUtils.getCellValue(row.getCell((short)2));
	           	 	            	record.setId(SeqUtil.getSeqNo());
	           	 	            	record.setCreateTime(DateUtil.getSysDateA());
	           	 	            	record.setTestTime(createTime);
	           	 	            	record.setDeviceId(deviceId);
	           	 	            	record.setCreateAuthor(authorId);
	           	 	            	if(ToolUtils.isNumeric(value) || StringUtils.isEmpty(deviceId)){
	           	 	            		record.setSugarValue(Double.parseDouble(value));
	           	 	            	}else{
	           	 	            		//
	           	 	            		logger.error(j+"记录："+deviceId+"："+value+"血糖值格式不正确或设备id为空，此条记录过滤");
	           	 	            		continue;
	           	 	            	}
	           	 	                list.add(record);
	           	 	            }
           	        	    }
                 	    }
                    }
             }
        }

		if(CollectionUtils.isEmpty(list)){
    		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_FILE_CONTENT_IS_EMPTY,"excel内容为空");
        }

        Map<String,Object> requestParam = new  HashMap<String,Object>();
        requestParam.put("tenantId",tenantId);
        requestParam.put("authorId",authorId);
        requestParam.put("list",list);
        Map<String,Object> rspMap = bloodSugarService.bloodsugarImport(requestParam);

        logger.debug("out bloodsugarImport----arg=="+JSON.toJSONString(rspMap));
        return new ResultModel<Object>(rspMap);
    }


    @ResponseBody
    @RequestMapping("/bloodsugar/patientListqry")
    public QueryModel<Map<String, Object>> getRecordPatientList(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
    	logger.info("in getRecordPatientList----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
		String startTime = requestParam.getString("startTime");
		//上传开始时间和 上传结束时间 校验
		if(!StringUtils.isEmpty(startTime) && !DateUtil.isValidDate(startTime,DateUtil.FORMAT_DAY)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "开始时间格式不正确");
		}
		String endTime = requestParam.getString("endTime");

		if(!StringUtils.isEmpty(endTime) && !DateUtil.isValidDate(endTime,DateUtil.FORMAT_DAY)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "结束格式不正确");
		}

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.putAll(requestParam);

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String authorId = (String) sessionMap.get("authorId");// 创建人
        paramMap.put("tenantId",tenantId);
        paramMap.put("authorId",authorId);

        List<Map<String, Object>> list= bloodSugarService.getRecordPatientList(paramMap);
        int total= 0;
        if(!CollectionUtils.isEmpty(list)){
        	total = bloodSugarService.getRecordPatientCount(paramMap);
        }
		logger.info("out getRecordPatientList----arg==" + list);
		return new QueryModel<Map<String,Object>>(list,total);
    }

    @ResponseBody
    @RequestMapping("/bloodsugar/userRecords")
    public ResultModel<Object> getRecordListByUserId(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
    	logger.info("in getRecordListByUserId----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        String userId = requestParam.getString("userId");
        if(StringUtils.isEmpty(userId)){
        	logger.debug("out getRecordListByUserId----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，患者ID不能为空");
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();


        String startTime = requestParam.getString("startTime");
		//上传开始时间和 上传结束时间 校验
		if(!StringUtils.isEmpty(startTime) && !DateUtil.isValidDate(startTime,DateUtil.FORMAT_DAY)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "开始时间格式不正确");
		}
		String endTime = requestParam.getString("endTime");

		if(!StringUtils.isEmpty(endTime) && !DateUtil.isValidDate(endTime,DateUtil.FORMAT_DAY)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "结束格式不正确");
		}

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        paramMap.putAll(requestParam);
        paramMap.put("tenantId",tenantId);
        paramMap.put("userId",userId);
        Map<String, Object> map= bloodSugarService.getRecordListByUserId(paramMap);
        /*if(!CollectionUtils.isEmpty(list)){
        	familyReportService.getGrowthPatientCount(paramMap);
        }*/
		logger.info("out getRecordListByUserId----arg==" + map);
		return new ResultModel<Object>(map);
    }

    @ResponseBody
    @RequestMapping("/device/query")
    public Map<String, Object> getDeviceList(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
    	logger.info("in getDeviceList----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		/*String type = requestParam.getString("type");
        if(StringUtils.isEmpty(type)){
        	logger.debug("out getDeviceList----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"设备类型不能为空");
        }*/

        Map<String, Object> paramMap = new HashMap<String, Object>();
        String jsonargs = requestParam.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonargs)){
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonargs);
            draw = jsonTable.getIntValue("draw");
            paramMap.put("page", jsonTable.getIntValue("start"));
            paramMap.put("rows", jsonTable.getIntValue("length"));
        }
        paramMap.putAll(requestParam);

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String authorId = (String) sessionMap.get("authorId");// 创建人
        paramMap.put("tenantId",tenantId);
        paramMap.put("authorId",authorId);

        List<Map<String, Object>> list= bloodSugarService.getDeviceList(paramMap);
        int total = 0;
        if(!CollectionUtils.isEmpty(list)){
        	total = bloodSugarService.getDeviceCount(paramMap);
        }

        Map<String, Object> retMap = new HashMap<String, Object>();
        retMap.put("draw", draw);
        retMap.put("recordsTotal", total);
        retMap.put("recordsFiltered", total);
        retMap.put("rows",list);

		logger.info("out getDeviceList----arg==" + list);
		return retMap;
    }
}
